import { defineComponent, onMounted } from 'vue'

export interface CustomIconOptions {
  scriptUrl?: string | string[]
  extraCommonProps?: { [key: string]: any }
}

export interface IconFontProps {
  type: string
}

function createScriptUrlElements(scriptUrls: string[], index: number = 0): void {
  const currentScriptUrl = scriptUrls[index]
  const script = document.createElement('script')
  script.setAttribute('src', currentScriptUrl)
  script.setAttribute('data-namespace', currentScriptUrl)
  if (scriptUrls.length > index + 1) {
    script.onload = () => {
      createScriptUrlElements(scriptUrls, index + 1)
    }
    script.onerror = () => {
      createScriptUrlElements(scriptUrls, index + 1)
    }
  }
  document.body.appendChild(script)
}

const create = (options: CustomIconOptions = {}) => {
  const { scriptUrl, extraCommonProps } = options

  let flag = false
  const createScript = () => {
    if (flag) return
    flag = true
    if (Array.isArray(scriptUrl)) {
      // 因为iconfont资源会把svg插入before，所以前加载相同type会覆盖后加载，为了数组覆盖顺序，倒叙插入
      createScriptUrlElements(scriptUrl.reverse())
    } else {
      createScriptUrlElements([scriptUrl])
    }
  }

  return defineComponent({
    props: {
      type: String
    },
    setup(props, ctx) {
      onMounted(createScript)

      return () => (
        <i role='img'>
          <svg>
            <use xlinkHref={`#${props.type}`} />
          </svg>
        </i>
      )
    }
  })
}

export default create
